package com.example.teesystem.common.websocket;

import com.example.teesystem.controller.PKController;
import com.example.teesystem.service.PKService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

/**
 * 通过事件监听器监听连接中断
 */
@Component
@RequiredArgsConstructor
public class PKDisconnectEventListener implements ApplicationListener<SessionDisconnectEvent> {
    private final PKService pkService;
    
    /**
     * 监听连接中断
     * 1. 获取 sessionId 并从 sessions 里获取 uid
     * 2. 更新 userInfos 和 groupInfos
     * @param event
     */
    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        // 1. 获取 sessionId 并从 sessions 里获取 uid
        String sessionId = event.getSessionId();
        Integer uid = PKController.sessions.get(sessionId);
        if(uid == null) {
            return;
        }
        
        // 2. 更新 userInfos 和 groupInfos
        pkService.disconnect(uid);
        PKController.sessions.remove(sessionId);
        
        PKController.printStatus();
    }
}
